package golf.stockdata.framework.util.hbm;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	
	private static SessionFactory sessionFactory;
	private static Logger logger = Logger.getLogger(HibernateUtil.class);
	
	static{
		
		logger.debug("Initializing Hibernate SessionFactory");

		try {
			Configuration configuration = new Configuration();
			
			logger.debug("Loading hibernate.cfg.xml ...");
			configuration.configure("hibernate.cfg.xml");

			logger.debug("Building ServiceRegistryBuilder ...");
			ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties());
			sessionFactory = configuration
					.buildSessionFactory(serviceRegistryBuilder
							.buildServiceRegistry());
			
		} catch (Throwable ex) {
			logger.error("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		logger.debug("<<< HibernateUtil");
	}
	
	public static SessionFactory getHibernateSessionFactory() {
		return sessionFactory;
	}

	public static Session createHibernatesession() {
		
		logger.debug(">>> createHibernatesession");
		
		Session hibernateSession;
		logger.debug("Openning the session ...");
		hibernateSession = sessionFactory.openSession();
		
		logger.debug("<<< createHibernatesession");
		
		return hibernateSession;
		
	}
}
